package cn.teamstack.logger.log;

import cn.teamstack.logger.entity.LogFile;
import cn.teamstack.logger.form.LogForm;
import cn.teamstack.logger.vo.LogFileWrapper;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: LogController
 * @Description:
 * @Author: Donaldhan
 * @Date: 2020-04-23 15:09
 */
@Slf4j
@RestController
@RequestMapping("/api/log")
@CrossOrigin
public class LogController {

    @GetMapping(value = "download")
    public void download(@RequestParam String path,
                         HttpServletResponse response) {
        try {
            path = URLDecoder.decode(path, "UTF-8");
            File file = new File(path);
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            // 3.将文件写入 response
            // 清空response
            response.reset();
            // 设置response的Header
            //设置文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
            //设置文件打下
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            log.error("LogController download error", e);
        }
    }

    /**
     * @param logForm
     * @param response
     * @return
     */
    @PostMapping(value = "historyList")
    public LogFileWrapper list(@RequestBody LogForm logForm,
                                     HttpServletResponse response) {
        LogFileWrapper logFileWrapper = new LogFileWrapper();
        try {
            // get file list where the path has   
            File file = new File(logForm.getDir());
            if(file.exists() && file.isDirectory()){
                File[]  fileList = file.listFiles();
                if(!ObjectUtils.isEmpty(fileList)){
                    Arrays.sort(fileList, new Comparator<File>() {
                        @Override
                        public int compare(File file1, File file2) {
                            return Long.compare(file2.lastModified(), file1.lastModified());
                        }
                    });
                    Integer days = ObjectUtils.isEmpty(logForm.getDays()) ? 2: logForm.getDays();
                    Long ttLTime = DateTime.now().minusDays(days).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).toDate().getTime();
                    List<File> tempFileList = Arrays.stream(fileList).filter(tempFile -> tempFile.lastModified() > ttLTime).collect(Collectors.toList());
                    String[] logCategoryList = logForm.getLogCategories().split(",");
                    tempFileList.forEach( tempFile -> {
                        LogFile logFile = LogFile.builder()
                                .filePath(tempFile.getAbsolutePath())
                                .fileName(tempFile.getName())
                                .fileSize(tempFile.length()).build();
                        Arrays.stream(logCategoryList).forEach(logNamePrefix ->{
                            if(logFile.getFileName().startsWith(logNamePrefix)){
                                logFileWrapper.putLogFile(logNamePrefix, logFile);
                            }
                        });
                    });
                    return logFileWrapper;
                }
            }
        } catch (Exception e) {
            log.error("LogController list error", e);
        }
        return logFileWrapper;
    }
}
